package com.bank.controller;

import com.bank.mapper.DetaileMapper;
import com.bank.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import entity.Detaile;
import entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class UserController {
    @Resource
    private UserMapper userMapper;
    @Resource
    private DetaileMapper detaileMapper;

    @PostMapping("/add/{uid}")
    @ApiOperation(value = "退款 必须先消费才能退款，消费100，只能退款5次",notes = "需传入 用户id")
    public String add(@PathVariable("uid")int uid){
        User user = userMapper.selectById(uid);
        QueryWrapper<Detaile> queryWrapper = new QueryWrapper<Detaile>();
        queryWrapper.eq("user_id",uid);
        List<Detaile> detailes = detaileMapper.selectList(queryWrapper);
        int i=0;
        for (entity.Detaile detaile : detailes) {
            i=i+detaile.getInfo();
        }
        if (i>0){
            user.setWallet(user.getWallet()+20.0);
            userMapper.updateById(user);
            detaileMapper.insert(new Detaile(null,uid,20.0,-2));
            return "退款20元";
        }else {
            return "当前没有消费，不能退款";
        }

    }

    @PostMapping("/sub/{uid}")
    @ApiOperation(value = "消费100 余额必须大于等于100",notes = "需传入 用户id")
    public String sub(@PathVariable("uid")int uid){
        User user = userMapper.selectById(uid);
        if (user.getWallet()>=100){
        user.setWallet(user.getWallet()-100.0);
        userMapper.updateById(user);
        detaileMapper.insert(new Detaile(null,uid,-100.0,10));
            return "消费100元";
        }else {
            return "余额不足，请充值";
        }
    }

    @GetMapping("/select/{uid}")
    @ApiOperation(value = "用户当前余额",notes = "需传入 用户id")
    public String select(@PathVariable("uid")int uid){
        User user1 = userMapper.selectById(uid);
        return "当前用户余额为:"+user1.getWallet();
    }

    @GetMapping("/detaile/{uid}")
    @ApiOperation(value = "用户明细",notes = "需传入 用户id")
    public String detaile(@PathVariable("uid")int uid){
        QueryWrapper<Detaile> queryWrapper = new QueryWrapper<Detaile>();
        queryWrapper.eq("user_id",uid);
        List<Detaile> list = detaileMapper.selectList(queryWrapper);
        StringBuffer stringBuffer = new StringBuffer();
        for (Detaile detaile : list) {
            if (detaile.getDetaile()>0){
                stringBuffer.append("退款20元;");
            }else if (detaile.getDetaile()<0){
                stringBuffer.append("消费100元;");
            }
        }
        User user = userMapper.selectById(uid);
        return "用户明细:"+stringBuffer+"用户余额:"+user.getWallet();
    }



}
